<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Linux,内网穿透,frp," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言frp 是一个高性能的反向代理应用，可以轻松地进行内网穿透，对外网提供服务，支持 TCP、UDP、HTTP、HTTPS 等协议类型，并且 web 服务支持根据域名进行路由转发。">
<meta name="keywords" content="Linux,内网穿透,frp">
<meta property="og:type" content="article">
<meta property="og:title" content="frp端口映射穿透内网">
<meta property="og:url" content="https://bingozb.github.io/55.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="前言frp 是一个高性能的反向代理应用，可以轻松地进行内网穿透，对外网提供服务，支持 TCP、UDP、HTTP、HTTPS 等协议类型，并且 web 服务支持根据域名进行路由转发。">
<meta property="og:image" content="https://bingozb.github.io/images/blog/55/architecture.png">
<meta property="og:updated_time" content="2017-09-23T17:20:13.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="frp端口映射穿透内网">
<meta name="twitter:description" content="前言frp 是一个高性能的反向代理应用，可以轻松地进行内网穿透，对外网提供服务，支持 TCP、UDP、HTTP、HTTPS 等协议类型，并且 web 服务支持根据域名进行路由转发。">
<meta name="twitter:image" content="https://bingozb.github.io/images/blog/55/architecture.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/55.html"/>





  <title>frp端口映射穿透内网 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/55.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                frp端口映射穿透内网
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-23T11:41:54+08:00">
                2017-09-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/战斗笔记/" itemprop="url" rel="index">
                    <span itemprop="name">战斗笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/55.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="55.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/55.html" class="leancloud_visitors" data-flag-title="frp端口映射穿透内网">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="/images/blog/55/architecture.png" alt="frp"></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>frp 是一个高性能的反向代理应用，可以轻松地进行内网穿透，对外网提供服务，支持 TCP、UDP、HTTP、HTTPS 等协议类型，并且 web 服务支持根据域名进行路由转发。</p>
<a id="more"></a>
<p>Github: <a href="https://github.com/fatedier/frp" target="_blank" rel="external">https://github.com/fatedier/frp</a></p>
<h2 id="安装frp"><a href="#安装frp" class="headerlink" title="安装frp"></a>安装frp</h2><p>Releases: <a href="https://github.com/fatedier/frp/releases" target="_blank" rel="external">https://github.com/fatedier/frp/releases</a></p>
<p>可以直接下载编译好的压缩包，在 Releases 页面中找到对应平台的压缩包，解压后就可以直接用，或者自己下载源码编译。</p>
<p>为了表示对作者的尊敬，我决定用 GO 编译。</p>
<h3 id="搭建GO环境"><a href="#搭建GO环境" class="headerlink" title="搭建GO环境"></a>搭建GO环境</h3><h4 id="安装依赖"><a href="#安装依赖" class="headerlink" title="安装依赖"></a>安装依赖</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"># Ubuntu</div><div class="line">$ sudo apt-get install bison ed gawk gcc libc6-dev make</div><div class="line"># CentOS</div><div class="line">$ sudo yum install gcc</div></pre></td></tr></table></figure>
<h4 id="下载go支持包"><a href="#下载go支持包" class="headerlink" title="下载go支持包"></a>下载go支持包</h4><p>各版本的下载地址 <a href="https://www.golangtc.com/static/go/" target="_blank" rel="external">https://www.golangtc.com/static/go/</a>，我使用的是当前最新的<code>1.9rc2</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ wget https://www.golangtc.com/static/go/1.9rc2/go1.9rc2.linux-amd64.tar.gz</div></pre></td></tr></table></figure>
<h4 id="解压go包"><a href="#解压go包" class="headerlink" title="解压go包"></a>解压go包</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ sudo tar -C /usr/local -xzf go1.9rc2.linux-amd64.tar.gz</div></pre></td></tr></table></figure>
<h4 id="添加环境变量和go工作区"><a href="#添加环境变量和go工作区" class="headerlink" title="添加环境变量和go工作区"></a>添加环境变量和go工作区</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ vim /etc/profile</div></pre></td></tr></table></figure>
<p>在文件的底部添加以下两行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">export PATH=$PATH:/usr/local/go/bin  </div><div class="line">export GOPATH=/usr/local/gopath</div></pre></td></tr></table></figure>
<p><code>:wq</code> 保存退出后，重新加载环境变量</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ source /etc/profile</div></pre></td></tr></table></figure>
<h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ mkdir -p /usr/local/gopath &amp;&amp; cd /usr/local/gopath</div><div class="line">$ vim test.go</div></pre></td></tr></table></figure>
<p>简单的打印测试：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">   fmt.Println(<span class="string">"Hello World!"</span>)  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>使用go编译运行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ go run test.go</div><div class="line">Hello World!</div></pre></td></tr></table></figure>
<p>至此，go环境搭建完毕。</p>
<h3 id="下载编译frp"><a href="#下载编译frp" class="headerlink" title="下载编译frp"></a>下载编译frp</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$ <span class="keyword">go</span> get github.com/fatedier/frp </div><div class="line">$ cd /usr/local/gopath/src/github.com/fatedier/frp/</div><div class="line">$ <span class="built_in">make</span></div></pre></td></tr></table></figure>
<h2 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h2><h3 id="创建frps配置文件"><a href="#创建frps配置文件" class="headerlink" title="创建frps配置文件"></a>创建frps配置文件</h3><p><code>make</code> 编译完成后，<code>frp</code>里会多出一个<code>bin</code>目录，放着<code>frpc</code>和<code>frps</code>，对应客户端和服务端的可执行文件。服务端上只需要用到 <code>frps</code>，可以删掉 <code>frpc</code>，客户端则相反。除此之外，还需要一个配置文件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ rm -rf frpc</div><div class="line">$ vim frps.ini</div></pre></td></tr></table></figure>
<p>详细的配置请看 <a href="https://github.com/fatedier/frp/blob/master/README_zh.md" target="_blank" rel="external">https://github.com/fatedier/frp/blob/master/README_zh.md</a>，官方的 README 介绍得非常详细。我再怎么写也没有官方的介绍更详细，这里直接贴我的配置。</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># frps.ini</span></div><div class="line"><span class="section">[common]</span></div><div class="line"><span class="attr">bind_addr</span> = <span class="number">0.0</span>.<span class="number">0.0</span></div><div class="line"><span class="attr">bind_port</span> = <span class="number">7001</span></div><div class="line"><span class="attr">vhost_http_port</span> = <span class="number">6666</span></div><div class="line"><span class="attr">dashboard_port</span> = <span class="number">7501</span></div><div class="line"><span class="attr">dashboard_user</span> = &#123;username&#125;</div><div class="line"><span class="attr">dashboard_pwd</span> = &#123;password&#125;</div><div class="line"><span class="attr">auth_token</span> = &#123;token&#125;</div><div class="line"><span class="attr">privilege_token</span> = &#123;privilege_token&#125;</div><div class="line"><span class="attr">privilege_mode</span> = <span class="literal">true</span></div></pre></td></tr></table></figure>
<p>我开启了<code>privilege_mode</code>，也就是开启了特权模式，这样服务端就不再需要配置每一条诸如 tcp、http 等的隧道，只需要把这个 frps 服务启动即可。</p>
<h3 id="运行服务端"><a href="#运行服务端" class="headerlink" title="运行服务端"></a>运行服务端</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">$ ./frps -c frps.ini</div><div class="line">2017/09/23 17:28:00 [I] [service.go:83] frps tcp listen on 0.0.0.0:7001</div><div class="line">2017/09/23 17:28:00 [I] [service.go:108] http service listen on 0.0.0.0:6666</div><div class="line">2017/09/23 17:28:00 [I] [service.go:134] Dashboard listen on 0.0.0.0:7501</div><div class="line">2017/09/23 17:28:00 [I] [main.go:112] Start frps success</div><div class="line">2017/09/23 17:28:00 [I] [main.go:114] PrivilegeMode is enabled, you should pay more attention to security issues</div></pre></td></tr></table></figure>
<p>一般会挂在后台运行这个服务，可以用 nohup：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ sudo nohup ./frps -c frps.ini &gt;/dev/null 2&gt;&amp;1 &amp;</div></pre></td></tr></table></figure>
<p>也许我有强迫症，我很讨厌生成的 nohup.out，所以使用 <code>&gt;/dev/null 2&gt;&amp;1</code> 来避免 shell 命令运行中有内容输出。</p>
<p>把 frps 服务跑起来后，公网服务器的配置就全部搞完了，当然，还得搞点手脚，让服务器开机自动启动这个服务，否则服务器重启就断开了。这个在 NAT 客户端上也是一样的，放到后面讲。</p>
<h3 id="创建frpc配置文件"><a href="#创建frpc配置文件" class="headerlink" title="创建frpc配置文件"></a>创建frpc配置文件</h3><p>接下来，需要在内网中的客户端做同样的操作，搭建go环境（如果你有兴趣的话）、下载编译frp，唯一不同的就是反过来删除 frps，保留 frpc。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">$ rm -rf frps</div><div class="line">$ vim frpc.ini</div></pre></td></tr></table></figure>
<p>由于开启了特权模式，所以，所有的隧道都可以直接在 frpc.ini 里配置。同样，直接贴上我的配置。</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># frpc.ini</span></div><div class="line"><span class="section">[common]</span></div><div class="line"><span class="attr">server_addr</span> = <span class="number">120.76</span>.<span class="number">207.187</span></div><div class="line"><span class="attr">server_port</span> = <span class="number">7001</span></div><div class="line"><span class="attr">auth_token</span> = &#123;token&#125;</div><div class="line"><span class="attr">privilege_token</span> = &#123;privilege_token&#125;</div><div class="line"><span class="section"></span></div><div class="line">[bingo_pi_web]</div><div class="line"><span class="attr">type</span> = http</div><div class="line"><span class="attr">local_port</span> = <span class="number">80</span></div><div class="line"><span class="attr">remote_port</span> = <span class="number">6666</span></div><div class="line"><span class="attr">custom_domains</span> = pi.bingo.ren</div><div class="line"><span class="section"></span></div><div class="line">[ssh]</div><div class="line"><span class="attr">type</span> = tcp</div><div class="line"><span class="attr">local_port</span> = <span class="number">22</span></div><div class="line"><span class="attr">remote_port</span> = <span class="number">3692</span></div></pre></td></tr></table></figure>
<p>这里我配置了两条隧道，一条是 http 类型的，一条是 tcp 的。然后，开启 frpc 服务即可。</p>
<h3 id="运行客户端"><a href="#运行客户端" class="headerlink" title="运行客户端"></a>运行客户端</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ sudo nohup ./frpc -c frpc.ini &gt;/dev/null 2&gt;&amp;1 &amp;</div></pre></td></tr></table></figure>
<h3 id="设置frp服务开机自启"><a href="#设置frp服务开机自启" class="headerlink" title="设置frp服务开机自启"></a>设置frp服务开机自启</h3><p>只需要在 <code>/etc/rc.local</code> 文件的最后，添加 frp 服务的启动命令即可。</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ vim /etc/rc.<span class="keyword">local</span></div></pre></td></tr></table></figure>
<p><code>exit 0</code> 是脚本退出的意思，只要将命令加在 <code>exit 0</code> 之前就可以开机启动了。</p>
<p>服务端，设置开机自启 frps 服务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">...</div><div class="line"></div><div class="line">nohup /usr/local/gopath/src/github.com/fatedier/frp/bin/frps -c /usr/local/gopath/src/github.com/fatedier/frp/bin/frps.ini &gt;/dev/null 2&gt;&amp;1 &amp;</div><div class="line"></div><div class="line">exit 0</div></pre></td></tr></table></figure>
<p>客户端，设置开机自启 frpc 服务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">...</div><div class="line"></div><div class="line">nohup /usr/local/etc/frp_0.13.0_linux_arm/frpc -c /usr/local/etc/frp_0.13.0_linux_arm/frpc.ini &gt;/dev/null 2&gt;&amp;1 &amp;</div><div class="line"></div><div class="line">exit 0</div></pre></td></tr></table></figure>
<p>设置完 reboot 重启一下，就会发现 frp 服务已经自动启动了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$ ps -ef | grep frp</div><div class="line">root       570     1  0 18:29 ?        00:00:00 /usr/local/etc/frp_0.13.0_linux_arm/frpc -c /usr/local/etc/frp_0.13.0_linux_arm/frpc.ini</div><div class="line">root       856   806  0 18:30 pts/0    00:00:00 grep --color frp</div></pre></td></tr></table></figure>
<h2 id="测试-1"><a href="#测试-1" class="headerlink" title="测试"></a>测试</h2><p>经过以上配置，正常情况下，在任何设备上，访问 <a href="https://pi.bingo.ren" target="_blank" rel="external">https://pi.bingo.ren</a>，就可以访问到内网 80 端口的 HTTP 服务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">$ curl https://pi.bingo.ren</div><div class="line">&lt;html&gt;</div><div class="line">    &lt;head&gt;</div><div class="line">	&lt;meta charset=&quot;utf-8&quot;/&gt;</div><div class="line">    &lt;/head&gt;</div><div class="line">    &lt;body&gt;</div><div class="line">       &lt;h1&gt;This is index page of Bingo&apos;s Raspberry PI. 🍺 &lt;/h1&gt;</div><div class="line">    &lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
<p>也可以在任何设备上通过 3692 端口连上内网的 sshd 服务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">$ ssh -p 3692 root@pi.bingo.ren</div><div class="line">Linux bingo 4.9.41-v7+ #1023 SMP Tue Aug 8 16:00:15 BST 2017 armv7l</div><div class="line">Last login: Sat Sep 23 17:23:29 2017 from 127.0.0.1</div><div class="line">root@bingo:~#</div></pre></td></tr></table></figure>
<p>如果穿透失败，请优先检查两台服务器上的 iptables，看是否有端口没有开放。确定不是防火墙的问题后，再一步一步排查问题。</p>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><p>贴一下 Nginx 的配置。</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># pi.bingo.ren.conf</span></div><div class="line"><span class="section">server</span> &#123;</div><div class="line">  <span class="attribute">listen</span> <span class="number">80</span>;</div><div class="line">  <span class="attribute">listen</span> <span class="number">443</span> ssl http2;</div><div class="line">  <span class="attribute">ssl_certificate</span> /usr/local/nginx/conf/ssl/pi.bingo.ren.crt;</div><div class="line">  <span class="attribute">ssl_certificate_key</span> /usr/local/nginx/conf/ssl/pi.bingo.ren.key;</div><div class="line">  <span class="attribute">ssl_protocols</span> TLSv1 TLSv1.<span class="number">1</span> TLSv1.<span class="number">2</span>;</div><div class="line">  <span class="attribute">ssl_ciphers</span> EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;</div><div class="line">  <span class="attribute">ssl_prefer_server_ciphers</span> <span class="literal">on</span>;</div><div class="line">  <span class="attribute">ssl_session_timeout</span> <span class="number">10m</span>;</div><div class="line">  <span class="attribute">ssl_session_cache</span> builtin:<span class="number">1000</span> shared:SSL:<span class="number">10m</span>;</div><div class="line">  <span class="attribute">ssl_buffer_size</span> <span class="number">1400</span>;</div><div class="line">  <span class="attribute">add_header</span> Strict-Transport-Security max-age=<span class="number">15768000</span>;</div><div class="line">  <span class="attribute">ssl_stapling</span> <span class="literal">on</span>;</div><div class="line">  <span class="attribute">ssl_stapling_verify</span> <span class="literal">on</span>;</div><div class="line">  <span class="attribute">server_name</span> pi.bingo.ren;</div><div class="line">  <span class="attribute">access_log</span> /data/wwwlogs/pi.bingo.ren_nginx.log combined;</div><div class="line">  <span class="attribute">index</span> index.html index.htm index.jsp;</div><div class="line">  <span class="attribute">root</span> /data/wwwroot/pi.bingo.ren;</div><div class="line"></div><div class="line">  <span class="attribute">location</span> <span class="regexp">~ </span>&#123;</div><div class="line">    <span class="attribute">proxy_pass</span> http://127.0.0.1:6666;</div><div class="line">    <span class="attribute">include</span> proxy.conf;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>用 Nginx 反向代理了 frp 的 http 服务，转发到 frps.ini 中配置的 <code>vhost_http_port</code> 6666 端口。</p>
<p>我遇到了一个坑，我在 README 中看到了 <code>vhost_https_port</code>，以为 HTTP 请求全部走 <code>vhost_http_port</code> 端口，而 HTTPS 请求需要走 <code>vhost_https_port</code> 端口。</p>
<p>于是，在配置 Nginx 的时候就把 <code>listen 80</code> 和 <code>listen 443</code> 写成两个 server。 80 端口的请求转发到 <a href="#">http://127.0.0.1:6666</a>，443 端口的请求转发到 <a href="#">https://127.0.0.1:8443</a>。</p>
<p>理论上似乎可行，但运行起来后， HTTPS 穿透失败了，一直都出现 502 异常。Github 上的 关于「nginx 反代 frp Https 502」的 issues 有好几个，但都没有解决的方案。作者认为，不使用 Nginx 直接请求 frps 的 https 端口是正常的，所以问题应该是在 nginx 那边，他似乎对很多人提这个 issues 感到很反感和无奈。</p>
<p>后面想到 Nginx 的502有可能是 SSL 证书的问题，Nginx 会验证被反代网站的证书。试了一下反代12306同样出现502，而换成百度就可以成功访问。成功锁定问题，就是内网的那台设备没有 SSL 证书。</p>
<p>于是试了一下自签，仍然会出现502。看来自签也不行，估计 Nginx 还会验 CA 证书，只有权威机构颁发的才能验证通过。</p>
<p>正当我想用 Let’s Encrypt，分一个域名去签的 SSL 证书的时候，突然发现，我的公网服务器已经签了一个证书了，为什么我的内网服务器还要再签一个？frps 和 frpc 的连接通讯应该不需要 HTTPS 了，又不是直接暴露的。</p>
<p>只要公网的域名上了 SSL 就够了，不管访问公网服务器的时候是 http 还是 https 请求，统一走 frp 的 http 隧道即可。</p>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p>frp 的更多玩法有待研究，目前已经满足了我的需求。一般我就只需要 http 和 tcp 隧道，udp 啥的等到有使用场景的时候再试试。</p>
<p>记得之前在网上看到，frp 是需要使用虚拟内存的，我还没去验证和配置。目前没发现有什么异常，Mark 一下，等出问题再解决吧。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/55.html" title="frp端口映射穿透内网">https://bingozb.github.io/55.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Linux/" rel="tag"># Linux</a>
          
            <a href="/tags/内网穿透/" rel="tag"># 内网穿透</a>
          
            <a href="/tags/frp/" rel="tag"># frp</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/56.html" rel="next" title="iOS解决CocoaPods安装OpenSSL失败的问题">
                <i class="fa fa-chevron-left"></i> iOS解决CocoaPods安装OpenSSL失败的问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/54.html" rel="prev" title="端口映射内网穿透方案探索">
                端口映射内网穿透方案探索 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装frp"><span class="nav-number">2.</span> <span class="nav-text">安装frp</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#搭建GO环境"><span class="nav-number">2.1.</span> <span class="nav-text">搭建GO环境</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#安装依赖"><span class="nav-number">2.1.1.</span> <span class="nav-text">安装依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#下载go支持包"><span class="nav-number">2.1.2.</span> <span class="nav-text">下载go支持包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#解压go包"><span class="nav-number">2.1.3.</span> <span class="nav-text">解压go包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#添加环境变量和go工作区"><span class="nav-number">2.1.4.</span> <span class="nav-text">添加环境变量和go工作区</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#测试"><span class="nav-number">2.1.5.</span> <span class="nav-text">测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#下载编译frp"><span class="nav-number">2.2.</span> <span class="nav-text">下载编译frp</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置"><span class="nav-number">3.</span> <span class="nav-text">配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建frps配置文件"><span class="nav-number">3.1.</span> <span class="nav-text">创建frps配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行服务端"><span class="nav-number">3.2.</span> <span class="nav-text">运行服务端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建frpc配置文件"><span class="nav-number">3.3.</span> <span class="nav-text">创建frpc配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行客户端"><span class="nav-number">3.4.</span> <span class="nav-text">运行客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置frp服务开机自启"><span class="nav-number">3.5.</span> <span class="nav-text">设置frp服务开机自启</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试-1"><span class="nav-number">4.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#补充"><span class="nav-number">5.</span> <span class="nav-text">补充</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">6.</span> <span class="nav-text">后话</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
